<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/24 0024
 * Time: 16:34
 */
namespace app\api\controller\v1;

use think\Controller;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use think\facade\Cache;
use think\facade\Request;
use Lcobucci\JWT\Parser;

class Base extends Controller
{
    public $uid;
    public $login_user;
    public $token;

    public function __construct()
    {
        parent::__construct();
        header('Content-type: application/json; charset=utf-8');
        $this->token = Request::param('token');

        $this->is_token();
    }

    // 判断token是否存在
    public function is_token()
    {
        if (empty($this->token)) {
            $this->error('token错误', 1001);
        }

        // 判断token是否已经过期
        $parse = (new Parser())->parse($this->token);
        $data  = json_decode($parse->getClaim('data'), true);
        $key = 'jwt_'.$data['id'];
        if (empty(Cache::get($key)) || empty($data)) {
            $this->error('您还未登录请先登录', 1000);
        }

        $this->uid = $data['id'];
        $this->reset_login();
    }

    // 重置登录缓存
    public function reset_login()
    {
        $key = 'jwt_'.$this->uid;
        Cache::set($key, Cache::get($key), 7*24*3600);
    }

    /**
     * 点击快速锁
     * @return [type] [description]
     */
    protected function clickLock()
    {
        $key = 'click_lock_'.get_ip();
        $redis = Cache::get($key);
        if (!empty($redis)) {
            $this->error('您点击太快了,请3秒后再试');
        } else {
            Cache::set($key, 1, 3);
        }
    }
}
